package com.talent.web.minio;

import cn.hutool.core.io.IoUtil;
import com.talent.web.config.minio.TlMinioProperties;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName：MinioFileService
 * @Author: hszhou
 * @Date: 2025/3/3 9:20
 * @Description: minio的上传功能
 */
@Slf4j
@Service
@RequiredArgsConstructor
@ConditionalOnProperty(name = "minio.enabled", havingValue = "true")
public class MinioTemplate {


    private final MinioClient minioClient;

    private final TlMinioProperties minioProperties;

    /**
     * 初始化minio客户端
     */
    @PostConstruct
    public void init() {
        try {
            createBucket(minioProperties.getBucket());
        } catch (Exception e) {
            log.error("初始化minio配置异常：", e);
        }
    }

    /**
     * 创建桶
     * @param bucketName 桶名
     * @return void
     */
    @SneakyThrows(Exception.class)
    public void createBucket(String bucketName) {
        boolean isExist = bucketExists(bucketName);
        if (!isExist) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }


    /**
     * 判断桶是否存在
     * @param bucketName 桶名
     * @return true:存在 false:不存在
     */
    @SneakyThrows(Exception.class)
    public  boolean bucketExists(String bucketName) {
        return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
    }

    /**
     * 获取全部桶
     * @return 桶信息
     */
    @SneakyThrows(Exception.class)
    public List<Bucket> getAllBuckets() {
        return minioClient.listBuckets();
    }

    /**
     * 文件上传
     * @param bucketName 桶名
     * @param file       文件
     * @return 文件url地址
     */
    @SneakyThrows(Exception.class)
    public  String upload(String bucketName, MultipartFile file) {
        final InputStream inputStream = file.getInputStream();
        final String fileName = file.getOriginalFilename();
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .stream(inputStream, file.getSize(), -1)
                .contentType(file.getContentType())
                .build());
        inputStream.close();
        return getFileUrl(bucketName, fileName);
    }

    /**
     * 删除文件
     *
     * @param bucketName 桶名
     * @param fileName   文件名
     * @return void
     */
    @SneakyThrows(Exception.class)
    public  void deleteFile(String bucketName, String fileName) {
        minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
    }

    /**
     * 下载文件
     * @param bucketName 桶名
     * @param objectName
     * @param response
     * @param fileName
     */
    @SneakyThrows(Exception.class)
    public  void download(String bucketName, String objectName, HttpServletResponse response, String fileName) {
        if(StringUtils.isEmpty(bucketName)){
            bucketName = minioProperties.getBucket();
        }
        // 获取对象的元数据
        final StatObjectResponse stat = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
        response.setContentType(stat.contentType());
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        InputStream is = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
        IoUtil.copy(is, response.getOutputStream());
        is.close();
    }

    /**
     * 获取minio文件的预览地址
     *
     * @param bucketName 桶名
     * @param fileName   文件名
     * @return 预览地址
     */
    @SneakyThrows(Exception.class)
    public  String getFileUrl(String bucketName, String fileName) {
        return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                .method(Method.GET)
                .bucket(bucketName)
                .object(fileName)
                .expiry(2, TimeUnit.HOURS)
                .build());
    }

}
